package middlewares

import (
	"net/http"

	"gitee.com/fkil555/gin-extend/app/result"
	"gitee.com/fkil555/gin-extend/conf"
	"gitee.com/fkil555/gin-extend/helpers/tokenhelper"
	"github.com/gin-gonic/gin"
)

func CheckToken() gin.HandlerFunc {
	return func(ctx *gin.Context) {

		headerKey := conf.GEConf.AppConfig.TokenHeaderKey
		if len(headerKey) <= 0 {
			headerKey = "Authorization"
		}
		header := ctx.Request.Header
		token := header.Get(headerKey)
		if len(token) <= 0 {
			ctx.Abort()
			ctx.JSON(http.StatusOK, result.Error(101, "need login token"))
			return
		}
		jwtToken, err := tokenhelper.ParseJwtToken(token)
		if err != nil || jwtToken == nil || jwtToken.Uid <= 0 {
			ctx.Abort()
			ctx.JSON(http.StatusOK, result.Error(102, "token parse fail"))
			return
		}
		ctx.Set("loginUserId", jwtToken.Uid)
		ctx.Set("loginExtends", jwtToken.ExtendInfo)

		ctx.Next()
	}
}

func AdminCheckToken() gin.HandlerFunc {
	return func(ctx *gin.Context) {

		headerKey := conf.GEConf.AppConfig.TokenHeaderAdminKey
		if len(headerKey) <= 0 {
			headerKey = "X-Token"
		}
		header := ctx.Request.Header
		token := header.Get(headerKey)
		if len(token) <= 0 {
			ctx.Abort()
			ctx.JSON(http.StatusOK, result.Error(101, "need login token"))
			return
		}
		jwtToken, err := tokenhelper.ParseJwtToken(token)
		if err != nil || jwtToken == nil || jwtToken.Uid <= 0 {
			ctx.Abort()
			ctx.JSON(http.StatusOK, result.Error(102, "token parse fail"))
			return
		}
		ctx.Set("loginUserId", jwtToken.Uid)
		ctx.Set("loginExtends", jwtToken.ExtendInfo)

		ctx.Next()
	}
}
